//
//  EMLoginViewController.m
//  EasyMoney
//
//  Created by zh on 2019/12/30.
//  Copyright © 2019 zh. All rights reserved.
//

#import "EMLoginViewController.h"
#import "EMSMSCodeView.h"
#import "EMLoginNavBarView.h"
#import "EMLoginInputView.h"
#import "EMLoginRequestModel.h"
#import "EMLoginResponseModel.h"
#import "EMVerifyCodeRequestModel.h"
#import "EMVerifyCodeResponseModel.h"
#import "EMAgreementsRequestModel.h"
#import "EMAgreementsResponseModel.h"
#import "UIViewController+ShowAlertController.h"
#import <Bugly/Bugly.h>
#import "EMLocationManager.h"

@interface EMLoginViewController () <EMLoginInputViewDelegate>

@property (nonatomic, strong) EMLoginNavBarView *navBar;
@property (nonatomic, strong) EMLoginInputView *input;

@property (nonatomic, strong) UILabel *textLabel;//请输入手机号
@property (nonatomic, strong) UIButton *nextBtn;//下一步
@property (nonatomic, strong) UILabel *agreementTipsLabel;//点击下一步表示同意用户协议／贷款协议
@property (nonatomic, strong) UILabel *agreementLabel;//协议

@property (nonatomic, assign) BOOL hasSendVerfiyCode;
@property (nonatomic, copy) NSString *mobile;
@property (nonatomic, copy) NSString *verfiyCode;

@property (nonatomic, copy) EMSuccessCallbackBlock successBlock;
@property (nonatomic, copy) EMFailedCallbackBlock failedBlock;

@end

@implementation EMLoginViewController

+ (BOOL)isSingleton
{
    return YES;
}

+ (BOOL)shouldPresent
{
    return YES;
}

+ (BOOL)shouldDimiss
{
    return YES;
}

+ (BOOL)isEnablePublicParams {
    return YES;
}

- (void)handleTransferPublicParams:(NSDictionary *)params {
    if ([params objectForKey:@"successBlock"]) {
        _successBlock = [params objectForKey:@"successBlock"];
    }
    if ([params objectForKey:@"failedBlock"]) {
        _failedBlock = [params objectForKey:@"failedBlock"];
    }
}

-(BOOL)handleWillOpenUrlWithParams:(NSDictionary *)params
{
    if ([params objectForKey:@"token"]) {
        _fromToken = [params objectForKey:@"token"];
    }
    
    if ([params objectForKey:@"fromoriginvc"]) {
        _fromViewController = [params objectForKey:@"fromoriginvc"];
    }
    
    if ([params objectForKey:@"refresh"]) {
        //https://github.wanda-group.net/wujianrong1/WDWiki/blob/master/WDSDUrlScheme.md
        NSString* ret = [params objectForKey:@"refresh"];
        
        if ([ret isEqualToString:@"0"]) {
            _fromToken = @"1";
        }
        
        if ([ret isEqualToString:@"1"])
        {
            _fromToken = nil;
            if ([ICENavigatorAction getPreviousViewContrllerFromStack] != nil) {
                _fromViewController = NSStringFromClass([[[ICENavigatorAction getRootNavigationViewController] topViewController] class]);
            }
        }
    }
    
    //如果来源于服务器的login统链 则清除token
    if (![params objectForKey:@"isLocal"]) {
        [EMUserInfoData clean];
        [[EMNetConfig sharedConfig] clearToken];
    }
    
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

- (void)setupUI
{
    self.navBar = [EMLoginNavBarView navBar];
    [self.navBar.closeBtn addTarget:self action:@selector(clickCloseBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.navBar];
    [self.navBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.mas_equalTo(EMNavBarHeight);
    }];
    
    self.textLabel = [[UILabel alloc] init];
    [self.view addSubview:self.textLabel];
    self.textLabel.font = FONT_PINGFANG_MEDIUM_(24);
    self.textLabel.text = NSLocalizedString(@"请输入手机号", nil);
    self.textLabel.textColor = ColorFromRGB(0x333333);
    [self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(24);
        make.right.mas_equalTo(-24);
        make.top.equalTo(self.navBar.mas_bottom).offset(35);
        make.height.mas_equalTo(34);
    }];
    
    self.input = [[EMLoginInputView alloc] init];
    self.input.delegate = self;
    [self.view addSubview:self.input];
    [self.input mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(24);
        make.right.mas_equalTo(-24);
        make.height.mas_equalTo(56);
        make.top.equalTo(self.textLabel.mas_bottom).mas_offset(36);
    }];
    
    //下一步
    self.nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextBtn.titleLabel.font = FONT_PINGFANG_MEDIUM_(16);
    self.nextBtn.layer.cornerRadius = 22;
    self.nextBtn.layer.masksToBounds = YES;
    [self.view addSubview:self.nextBtn];
    UIImage *image = [UIImage gradientImageSize:CGSizeMake(SCREEN_WIDTH-48-48, 44) colors:@[[UIColor colorwithHexString:@"#36B2FF"],[UIColor colorwithHexString:@"#2F5AFF"]] startPoint:CGPointMake(0, 22) endPoint:CGPointMake(SCREEN_WIDTH-48-48, 22)];
    [self.nextBtn setBackgroundImage:image forState:UIControlStateNormal];
    [self.nextBtn setTitle:NSLocalizedString(@"下一步", nil) forState:UIControlStateNormal];
    [self.nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.nextBtn setBackgroundImage:[UIImage imageWithColor:[UIColor colorwithHexString:@"#2761FF" alpha:0.5]] forState:UIControlStateDisabled];
    [self.nextBtn setEnabled:NO];
    [self.nextBtn addTarget:self action:@selector(clickNextBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(48);
        make.right.mas_equalTo(-48);
        make.height.mas_equalTo(44);
        make.top.equalTo(self.input.mas_bottom).mas_offset(24);
    }];
    
    //协议说明
    self.agreementTipsLabel = [[UILabel alloc] init];
    [self.view addSubview:self.agreementTipsLabel];
    self.agreementTipsLabel.textAlignment = NSTextAlignmentCenter;
    self.agreementTipsLabel.font = FONT_PINGFANG_REGULAR_(14);
    self.agreementTipsLabel.textColor = ColorFromRGB(0x999999);
    self.agreementTipsLabel.text = NSLocalizedString(@"点击下一步表示同意用户协议／贷款协议", nil);
    [self.agreementTipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(24);
        make.right.mas_equalTo(-24);
        make.top.equalTo(self.nextBtn.mas_bottom).mas_offset(28);
    }];
    //协议
    self.agreementLabel = [[UILabel alloc] init];
    [self.view addSubview:self.agreementLabel];
    self.agreementLabel.font = FONT_PINGFANG_REGULAR_(14);
    self.agreementLabel.textColor = ColorFromRGB(0x2f5aff);
    self.agreementLabel.text = NSLocalizedString(@"用户协议全文", nil);
    [self.agreementLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.agreementTipsLabel);
        make.top.equalTo(self.agreementTipsLabel.mas_bottom).mas_offset(2);
    }];
    UIButton *agreeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [agreeBtn addTarget:self action:@selector(clickAgreementBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:agreeBtn];
    [agreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.agreementLabel);
    }];
}

- (void)clickNextBtn:(UIButton *)sender
{
    if (self.hasSendVerfiyCode == NO) {
        self.textLabel.text = NSLocalizedString(@"请输入验证码", nil);
        [self showVerifyCode];
    } else
    {
        [self requestLogin];
    }
}

- (void)showVerifyCode
{
    self.mobile = [self.input currentInputString];
    [self.input showVerifyCode];
}

- (void)requestLogin
{
    if (self.mobile.length <= 0 || self.hasSendVerfiyCode == NO || [self.input currentInputString].length <= 0) {
        return;
    }
    [SVProgressHUD showWithStatus:NSLocalizedString(@"加载中", nil)];
    EMLoginRequestModel *req = [EMLoginRequestModel new];
    req.mobile = self.mobile;
    req.regChannel = EMRegChannel;
    req.riskData = [EMRiskDataModel rickData];
#ifdef DEBUG
     req.verifyCode = self.verfiyCode;
#else
    req.verifyCode = [self.input currentInputString];
#endif
    __weak typeof(self)weakSelf = self;
    [req requestSuccess:^(EMLoginResponseModel *response, NSString * _Nonnull message) {
        [SVProgressHUD dismiss];
        //success
        [EMUserInfoData clean];
        [[EMNetConfig sharedConfig] clearToken];
        [[EMNetConfig sharedConfig] setRefreshToken:response.refreshToken];
        [[EMNetConfig sharedConfig] setToken:response.accessToken];
        UserInfoShared.mobile = self.mobile;
        UserInfoShared.token = response.accessToken;
        UserInfoShared.userId = response.userId.stringValue;
        [EMUserInfoData update];
        NSString *userId = UserInfoShared.userId;
        if (userId.length > 0) {
            [Bugly setUserIdentifier:userId];
        }
        if (self.successBlock) {
            self.successBlock(0, nil);
        }
         [[NSNotificationCenter defaultCenter] postNotificationName:EMLoginNofitication object:nil];
        NSLog(@"login success:%@",response);
        //正常跳转
        if(SAFE_STRING(self.fromToken).length > 0)
        {
            ICEOpenUrl(@"emoney://home?page=1");
        }
        else if (SAFE_STRING(self.fromViewController).length > 0) {
            [weakSelf popToViewControllers:@[self.fromViewController]];
        }
        else
        {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
        [ICENavigator notifyToUrlSchemeQueue];
        
    } failure:^(NSInteger errorCode, NSString * _Nonnull errorMessage, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:errorMessage];
        [SVProgressHUD dismissWithDelay:1.5];
        
    }];
}

- (void)clickCloseBtn:(UIButton *)btn
{
    [ICENavigator queuePopAllUrlscheme];
    if (_failedBlock) {
         _failedBlock(0, nil);
     }
    if (SAFE_STRING(_fromToken).length > 0) {
         ICEOpenUrl(@"emoney://home?page=1");
         return;
     }
     [self.navigationController emDismissViewController];
}

- (void)clickAgreementBtn:(UIButton *)btn
{
    [SVProgressHUD showWithStatus:NSLocalizedString(@"加载中", nil)];
    EMAgreementsRequestModel *request = [[EMAgreementsRequestModel alloc]init];
    request.type = @"login";
    [request requestSuccess:^(EMAgreementsResponseModel *response, NSString * _Nonnull message) {
        [SVProgressHUD showSuccessWithStatus:message];
        [SVProgressHUD dismissWithDelay:1.5];
        [self showAgreementActionSheet:response];

    } failure:^(NSInteger errorCode, NSString * _Nonnull errorMessage, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:errorMessage];
        [SVProgressHUD dismissWithDelay:1.5];
    }];


}

- (void)showAgreementActionSheet:(EMAgreementsResponseModel *)model{

    NSMutableArray *actionArray = [[NSMutableArray alloc]init];
    for (EMAgreementItemModel *obj in model.agreements) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:SAFE_STRING(obj.name) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (obj.url.length > 0) {
                NSString *webUrl = [NSString stringWithFormat: @"emoney://web?url=%@",obj.url];
                ICEOpenUrl(webUrl);
            }
        }];
        [actionArray addObject:action];
    }
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        return ;
    }];
    [actionArray addObject:cancel];
    [self showActionSheetMessage:@"" withTitle:@"" withActions:actionArray];
}

#pragma mark - EMLoginInputViewDelegate

- (void)inputView:(EMLoginInputView *)inputView textfieldChanged:(UITextField *)textfield
{
    if (textfield.text.length > 0 && self.nextBtn.enabled == NO) {
        self.nextBtn.enabled = YES;
    } else if (textfield.text.length <= 0 && self.nextBtn.enabled == YES) {
        self.nextBtn.enabled = NO;
    }
}

- (void)inputView:(EMLoginInputView *)inputView clickSmsBtn:(UIButton *)smsBtn inSMSCodeView:(EMSMSCodeView *)codeView
{
    [self.view endEditing:YES];
    [smsBtn setEnabled:NO];
    EMVerifyCodeRequestModel* authReq = [[EMVerifyCodeRequestModel alloc] init];
    NSString *mobile = self.mobile;
    authReq.mobile = mobile;
    authReq.regChannel = EMRegChannel;
    self.textLabel.text = [NSString stringWithFormat:NSLocalizedString(@"验证码已发送至%@", nil),mobile];
    [SVProgressHUD showWithStatus:NSLocalizedString(@"加载中", nil)];
    [authReq requestSuccess:^(EMVerifyCodeResponseModel *response, NSString *message) {
        [SVProgressHUD showSuccessWithStatus:message];
        [SVProgressHUD dismissWithDelay:1.5];
        [codeView startTimerWithDuration:response.ttl];
        self.mobile = mobile;
        self.hasSendVerfiyCode = YES;
        #ifdef DEBUG
        self.verfiyCode = response.verifyCode;
        [inputView setText:response.verifyCode];
        #else
        [inputView setText:nil];
        #endif
    } failure:^(NSInteger errorCode, NSString *errorMessage, NSError *error) {
        [SVProgressHUD showErrorWithStatus:errorMessage];
        [SVProgressHUD dismissWithDelay:1.5];
        [smsBtn setEnabled:YES];
    }];
}

@end
